package com.company.cloud.club.modules.controller;


import com.alibaba.fastjson.JSON;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;
import com.company.cloud.club.modules.core.dto.MessageParams;
import com.company.cloud.club.modules.core.dto.Result;
import com.company.cloud.club.modules.core.dto.project.CaseDto;
import com.company.cloud.club.modules.core.dto.project.SurveyDto;
import com.company.cloud.club.modules.core.util.ValidateUtil;
import com.company.cloud.club.modules.db.dao.ProjectCaseMapper;
import com.company.cloud.club.modules.db.domain.*;
import com.company.cloud.club.modules.dto.IdQuery;
import com.company.cloud.club.modules.dto.JsPatchParam;
import com.company.cloud.club.modules.dto.LayTableResult;
import com.company.cloud.club.modules.dto.MassageConstant;
import com.company.cloud.club.modules.dto.product.OrderParam;
import com.company.cloud.club.modules.dto.project.ProjectBo;
import com.company.cloud.club.modules.dto.project.ProjectCaseBrandVo;
import com.company.cloud.club.modules.dto.project.ProjectOrderVo;
import com.company.cloud.club.modules.dto.project.UserInvitationSaveParam;
import com.company.cloud.club.modules.service.*;
import com.company.cloud.club.modules.utils.DataUtils;
import com.company.cloud.club.modules.utils.JWTUtil;
import com.company.cloud.club.modules.utils.LoginContextUtils;
import com.company.cloud.common.asserts.ValidatorUtils;
import com.company.cloud.common.auth.annotation.StaffLogc;
import com.company.cloud.common.sign.URLCoderUtils;
import com.company.cloud.common.utils.HttpContextUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import net.coobird.thumbnailator.Thumbnails;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.regex.Pattern;

/**
 * @author Fangjun
 */
@Api(tags = "项目对接")
@RequestMapping("/project")
@AllArgsConstructor
@RestController
public class ProjectController {

    @Autowired
    private ProjectService projectService;

    @Autowired
    private ProjectOrderService projectOrderService;

    @Autowired
    private ProjectCaseBrandService projectCaseBrandService;

    @Autowired
    private BannerService bannerService;

    @Autowired
    private ProjectCaseMapper projectCaseMapper;

    @Autowired
    private ProjectApplyService projectApplyService;

    @Autowired
    private ProjectOptionService projectOptionService;

    @Autowired
    private ProjectCaseService projectCaseService;

    @Autowired
    private MessageService messageService;

    //banner列表
    @GetMapping(value = "banner")
    public Result banner() {
        List<Banner> dtoList = projectService.bannerList();
        return Result.ok(dtoList);
    }

    @GetMapping(value = "bannerVo")
    public Result bannerVo() {
        List<Banner> dtoList = projectService.bannerList();
        List<Banner> dtoLists = new ArrayList<>();
        dtoList.forEach(m -> {
            if (m.getType().equals("项目")) {
                dtoLists.add(m);
            }
        });
        return Result.ok(dtoLists);
    }

    @GetMapping(value = "banner/detail")
    public Result bannerDetail(@Valid @ModelAttribute IdQuery query) {
        String id = query.getId();
        final Banner byId = bannerService.getById(id);
        if (ValidateUtil.isEmpty(byId)) {
            throw new RuntimeException("banner不存在");
        }
        return Result.ok(byId);
    }

    @GetMapping(value = "banner/del")
    @StaffLogc(title = "删除Banner", action = "删除Banner", actionAdo = "项目对接")
    public Result bannerDel(@Valid @ModelAttribute IdQuery query) {
        return Result.ok(projectCaseMapper.Bannerdelete(query.getId()));
    }

    @PostMapping(value = "banner/save")
    @StaffLogc(title = "保存Banner", action = "保存Banner", actionAdo = "项目对接")
    public Result list(@RequestBody @Valid Banner params) {
        Banner banner = bannerService.getById(params.getId());
        if (ValidateUtil.isEmpty(banner)) {
            Banner project = new Banner(0);
            BeanUtils.copyProperties(params, project);
            params.setTimeCreated(System.currentTimeMillis());
            params.setTimeModified(System.currentTimeMillis());
        }
        return Result.ok(bannerService.saveOrUpdate(params));
    }

    @PostMapping(value = "survey/list")
    public Result survey(HttpServletRequest request) {
        SurveyDto surveyDto = new SurveyDto();
        surveyDto.addMechanismList("企业");
        surveyDto.addMechanismList("行业协会");
        surveyDto.addMechanismList("教育机构");
        surveyDto.addMechanismList("个人");
        surveyDto.addMechanismList("政府机构");
        surveyDto.addMechanismList("艺术机构");
        surveyDto.addMechanismList("工作室");
        surveyDto.addMechanismList("其它");

        surveyDto.addIndustryList("文化旅游");
        surveyDto.addIndustryList("品牌");
        surveyDto.addIndustryList("公关/活动");
        surveyDto.addIndustryList("娱乐游戏");
        surveyDto.addIndustryList("商业地产");
        surveyDto.addIndustryList("文化传媒");
        surveyDto.addIndustryList("广告创意");
        surveyDto.addIndustryList("教育培训");
        surveyDto.addIndustryList("其它");

        surveyDto.addBudgetList("3万以下");
        surveyDto.addBudgetList("3-10万");
        surveyDto.addBudgetList("10万-20万");
        surveyDto.addBudgetList("20万-50万");
        surveyDto.addBudgetList("50万-100万");
        surveyDto.addBudgetList("100万以上");

        return Result.ok(surveyDto);
    }

    @PostMapping(value = "push/list")
    public Result projectPush(HttpServletRequest request) {
        SurveyDto surveyDto = new SurveyDto();

        surveyDto.addIndustryList("艺术展览");
        surveyDto.addIndustryList("场地合作");
        surveyDto.addIndustryList("联名活动");
        surveyDto.addIndustryList("IP授权");
        surveyDto.addIndustryList("颁奖评选");
        surveyDto.addIndustryList("专题创作");
        surveyDto.addIndustryList("商务活动");

        surveyDto.addBudgetList("3万以下");
        surveyDto.addBudgetList("3-10万");
        surveyDto.addBudgetList("10万-20万");
        surveyDto.addBudgetList("20万-50万");
        surveyDto.addBudgetList("50万-100万");
        surveyDto.addBudgetList("100万以上");
        return Result.ok(surveyDto);
    }

    //案列列表接口
    @GetMapping(value = "list")
    public LayTableResult list(@Valid @ModelAttribute Project params) {
        Integer begin = params.getCurrentPage();
        Integer pageSize = params.getPageSize();
        Integer currentPage = (begin - 1) * pageSize;
     /*   IPage<Project> page = projectService.page(new Page<>(currentPage, pageSize), new QueryWrapper<>(params));
        int total = projectService.count(new QueryWrapper<>(params));*/
        List<Project> list = projectCaseMapper.listPage(currentPage, pageSize);
        Integer count = projectCaseMapper.proCount();
        // List<Project> records = page.getRecords();
        return new LayTableResult<>(0, "获取项目列表", list, count);
    }

    @PostMapping(value = "case/edit")
    @StaffLogc(title = "案列修改", action = "案列修改", actionAdo = "案列列表")
    public Result list(@RequestBody @Valid ProjectCaseBrand params) {
        ProjectCaseBrand projectCaseBrand = projectCaseBrandService.getById(params.getId());
        if (ValidateUtil.isEmpty(projectCaseBrand)) {
            ProjectCaseBrand project = new ProjectCaseBrand(0);

            BeanUtils.copyProperties(params, project);
            params.setTimeCreated(System.currentTimeMillis());
            params.setTimeModified(System.currentTimeMillis());
        }
        return Result.ok(projectCaseBrandService.saveOrUpdate(params));
    }

    @GetMapping(value = "case/del")
    @StaffLogc(title = "案列删除", action = "案列删除", actionAdo = "案列列表")
    public Result caseDel(@Valid @ModelAttribute IdQuery query) {
        return Result.ok(projectCaseMapper.caseDelete(query.getId()));
    }

    @GetMapping(value = "detail")
    public Result detail(@Valid @ModelAttribute IdQuery query) {
        String id = query.getId();
        Project project = projectService.getById(id);
        if (ValidateUtil.isEmpty(project)) {
            throw new RuntimeException("项目不存在");
        }
        return Result.ok(project);
    }

    @PostMapping(value = "edit")
    @StaffLogc(title = "项目修改", action = "项目修改", actionAdo = "项目对接")
    public Result edit(@Valid @RequestBody Project bo) {
        Project project1 = projectService.getById(bo.getId());
        if (ValidateUtil.isEmpty(project1)) {
            Project project = new Project(0);
            long timeStamp = System.currentTimeMillis();  //获取当前时间戳,也可以是你自已给的一个随机的或是别人给你的时间戳(一定是long型的数据)
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//这个是你要转成后的时间的格式
            String mtime = sdf.format(new Date(timeStamp));   // 时间戳转换成时间
            project.setMtime(mtime);
            BeanUtils.copyProperties(bo, project);
            Integer currentUserId = LoginContextUtils.getUserId();
            bo.setTimeCreated(System.currentTimeMillis());
            bo.setTimeModified(System.currentTimeMillis());
            bo.setUid(currentUserId);
        }
        boolean flag = projectService.saveOrUpdate(bo);
        if (!flag) {
            throw new RuntimeException("项目保存失败");
        }
        return Result.ok(bo.getId());
    }

    //项目删除
    @PostMapping(value = "del")
    @StaffLogc(title = "项目删除", action = "项目删除", actionAdo = "项目对接")
    public Result Del(@Valid @RequestBody IdQuery query) {
        return Result.ok(projectCaseMapper.projectDelete(query.getId()));
    }

    @PostMapping(value = "submit")
    @StaffLogc(title = "项目添加", action = "项目添加", actionAdo = "项目对接")
    public Result submit(@Valid @RequestBody ProjectBo bo) {
        Project project = new Project(0);
        long timeStamp = System.currentTimeMillis();  //获取当前时间戳,也可以是你自已给的一个随机的或是别人给你的时间戳(一定是long型的数据)
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//这个是你要转成后的时间的格式
        String mtime = sdf.format(new Date(timeStamp));   // 时间戳转换成时间
        project.setMtime(mtime);
        BeanUtils.copyProperties(bo, project);
        project.setMdesc(bo.getDesc());
        project.setMtype(bo.getType());
        Integer currentUserId = LoginContextUtils.getUserId();
        project.setUid(currentUserId);
        boolean flag = projectService.submit(project);
        if (!flag) {
            throw new RuntimeException("项目保存失败");
        }
        return Result.ok(project.getId());
    }

    //案例展示列表
    @GetMapping(value = "case/list")
    public LayTableResult proCaseList(@Valid @ModelAttribute ProjectCaseBrand params) {
        Integer begin = params.getCurrentPage();
        Integer pageSize = params.getPageSize();
        Integer currentPage = (begin - 1) * pageSize;
        String caseId = params.getCaseId();
        List<ProjectCaseBrand> list = projectCaseMapper.CaseListPage(caseId, currentPage, pageSize);
        Integer count = projectCaseMapper.CaseListCount(caseId);
        return new LayTableResult<>(0, "获取案列列表", list, count);
    }

    @GetMapping(value = "caseList")
    public Result caseList() {
        List<CaseDto> list = projectService.caseList();
        list.forEach(m -> {
            List<ProjectCaseBrand> projectCases = projectCaseMapper.selectCaseId(m.getId());
            for (ProjectCaseBrand brand : projectCases) {
                String pureBrand = DataUtils.removeHtmlLabel(brand.getBrand());
                brand.setPureBrand(pureBrand.length() <= 50 ? pureBrand : pureBrand.substring(0, 49));
            }
            m.setChildren(projectCases);
        });
        return Result.ok(list);
    }

    @GetMapping(value = "case/detail")
    public Result caseDetail(@Valid @ModelAttribute IdQuery bo) {
        final ProjectCaseBrand byId = projectCaseBrandService.getById(bo.getId());

        if (ValidateUtil.isEmpty(byId)) {
            throw new RuntimeException("未找到此数据！！！");
        }

        ProjectCaseBrandVo project = new ProjectCaseBrandVo();
        BeanUtils.copyProperties(byId, project);
        long timeStamp = byId.getTimeCreated() / 1000;  //获取当前时间戳,也可以是你自已给的一个随机的或是别人给你的时间戳(一定是long型的数据)
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//这个是你要转成后的时间的格式
        String mtime = sdf.format(new Date(timeStamp));   // 时间戳转换成时间
        project.setCtime(mtime);
        return Result.ok(project);
    }

    //申请人列表
    @GetMapping(value = "apply/list")
    public LayTableResult proApplyList(@Valid @ModelAttribute ProjectApply params) {
        Integer begin = params.getCurrentPage();
        Integer pageSize = params.getPageSize();
        Integer currentPage = (begin - 1) * pageSize;
        List<ProjectApply> list = projectCaseMapper.ApplyListPage(currentPage, pageSize);
        Integer count = projectCaseMapper.ApplyListCount();
        return new LayTableResult<>(0, "获取案列列表", list, count);
    }

    //申请人修改
    @PostMapping(value = "apply/edit")
    @StaffLogc(title = "申请人修改", action = "申请人修改", actionAdo = "申请列表")
    public Result proApplyEdits(@Valid @RequestBody ProjectApply params) {
        ProjectApply apply = projectApplyService.getById(params.getId());
        if (ValidateUtil.isEmpty(apply)) {
            ProjectApply project = new ProjectApply(0);
            long timeStamp = System.currentTimeMillis();  //获取当前时间戳,也可以是你自已给的一个随机的或是别人给你的时间戳(一定是long型的数据)
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//这个是你要转成后的时间的格式
            String mtime = sdf.format(new Date(timeStamp));   // 时间戳转换成时间
            project.setMtime(mtime);
            BeanUtils.copyProperties(params, project);
            Integer currentUserId = LoginContextUtils.getUserId();
            params.setTimeCreated(System.currentTimeMillis());
            params.setTimeModified(System.currentTimeMillis());
            params.setUid(currentUserId);
        }
        final boolean b = projectApplyService.saveOrUpdate(params);
        if (!b) {
            throw new RuntimeException("修改或添加失败");
        }
        return Result.ok();
    }

    //申请人删除
    @PostMapping(value = "apply/del")
    @StaffLogc(title = "申请人删除", action = "申请人删除", actionAdo = "申请列表")
    public Result proApplyDel(@Valid @RequestBody IdQuery query) {
        return Result.ok(projectCaseMapper.ApplyDelete(query.getId()));
    }

    @GetMapping(value = "apply/detail")
    public Result applyDetail(@Valid @ModelAttribute IdQuery query) {
        String id = query.getId();
        final ProjectApply apply = projectApplyService.getById(id);
        if (ValidateUtil.isEmpty(apply)) {
            throw new RuntimeException("当前不存在");
        }
        return Result.ok(apply);
    }

    //申请人修改zhuangtai状态  审核
    @PostMapping(value = "apply/edit/state")
    @StaffLogc(title = "申请人审核", action = "申请人审核", actionAdo = "申请列表")
    public Result proApplyEdit(@Valid @RequestBody ProjectApply params) {
        final boolean b = projectCaseMapper.applyUpdate(params.getMtype(), params.getId());
        if (!b) {
            throw new RuntimeException("修改或添加失败");
        }
        return Result.ok();
    }

    //申请类型行业列表
    @GetMapping(value = "option/list")
    public LayTableResult optionList(@Valid @ModelAttribute ProjectOption params) {
        Integer begin = params.getCurrentPage();
        Integer pageSize = params.getPageSize();
        Integer currentPage = (begin - 1) * pageSize;
        List<ProjectOption> list = projectCaseMapper.OptionListPage(currentPage, pageSize);
        Integer count = projectCaseMapper.OptionListCount();
        return new LayTableResult<>(0, "获取类型行业列表", list, count);
    }

    //申请类型行业添加
    @PostMapping(value = "option/commit")
    public Result proOptionEdit(@Valid @RequestBody ProjectOption params) {
        ProjectOption apply = projectOptionService.getById(params.getId());
        if (ValidateUtil.isEmpty(apply)) {
            ProjectOption option = new ProjectOption(0);
            long timeStamp = System.currentTimeMillis();  //获取当前时间戳,也可以是你自已给的一个随机的或是别人给你的时间戳(一定是long型的数据)
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//这个是你要转成后的时间的格式
            String mtime = sdf.format(new Date(timeStamp));   // 时间戳转换成时间
            option.setMtime(mtime);
            BeanUtils.copyProperties(params, option);
            params.setTimeCreated(System.currentTimeMillis());
            params.setTimeModified(System.currentTimeMillis());
        }
        return Result.ok(projectOptionService.saveOrUpdate(params));
    }

    //申请类型行业删除
    @StaffLogc(title = "申请类型行业删除", action = "申请类型行业删除", actionAdo = "申请类型行业")
    @PostMapping(value = "option/del")
    public Result optionDel(@Valid @RequestBody IdQuery query) {
        String id = query.getId();
        return Result.ok(projectCaseMapper.optionDels(id));
    }

    //申请类型行业详情
    @GetMapping(value = "option/detail")
    public Result optionDetail(@Valid @ModelAttribute IdQuery query) {
        String id = query.getId();
        final ProjectOption apply = projectOptionService.getById(id);
        if (ValidateUtil.isEmpty(apply)) {
            throw new RuntimeException("当前不存在");
        }
        return Result.ok(apply);
    }

    //申请人查询状态
    @GetMapping(value = "apply/detailVto")
    public Result optionDetailVo() {
        Integer currentUserId = LoginContextUtils.getUserId();
        final ProjectApply project = projectCaseMapper.getprijectOne(currentUserId);
        if (ValidateUtil.isEmpty(project)) {
            Map map = new HashMap();
            map.put("mtype", 3);
            return Result.ok(map);
        }
        return Result.ok(project);
    }

    //订单列表
    @GetMapping(value = "order/list")
    public LayTableResult OrderList(@Valid @ModelAttribute ProjectOrder params) {
        Integer begin = params.getCurrentPage();
        Integer pageSize = params.getPageSize();
        Integer currentPage = (begin - 1) * pageSize;
        String projectId = params.getProjectId();
        List<ProjectOrder> list = projectCaseMapper.OrderListPage(projectId, currentPage, pageSize);
        Integer count = projectCaseMapper.OrderListCount(projectId);
        return new LayTableResult<>(0, "获取订单列表", list, count);
    }

    //接项目添加
    @PostMapping(value = "order/add")
    public Result orderAdd(@Valid @RequestBody IdQuery query) {
        Integer currentUserId = LoginContextUtils.getUserId();
        final ProjectApply projectApply = projectCaseMapper.getprijectOne(currentUserId);
        if (ValidateUtil.isEmpty(projectApply)) {
            throw new RuntimeException("无法进行接收项目！！！原因是未存在你申请的公司名称");
        }
        final Project byId = projectService.getById(query.getId());
        if (ValidateUtil.isEmpty(byId)) {
            throw new RuntimeException("此项目未存在！！！");
        }
        if (currentUserId.equals(byId.getUid())) {
            throw new RuntimeException("无法进行接取自己已发的项目");
        }
        final ProjectOrder projectOrder = projectCaseMapper.getProjectOrder(query.getId());
        if (ValidateUtil.isValid(projectOrder)) {
            throw new RuntimeException("已接此项目，无法重复接此项目！！！");
        }
        ProjectOrder option = new ProjectOrder(0);
        option.setCompanyName(projectApply.getCompanyName());
        option.setEmail(projectApply.getEmail());
        option.setMtype("已接项目");
        option.setPhone(projectApply.getPhone());
        option.setProjectId(byId.getId());
        option.setPosition(projectApply.getPosition());
        option.setContacts(projectApply.getContacts());
        option.setUid(currentUserId);
        long timeStamp = System.currentTimeMillis();  //获取当前时间戳,也可以是你自已给的一个随机的或是别人给你的时间戳(一定是long型的数据)
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//这个是你要转成后的时间的格式
        String mtime = sdf.format(new Date(timeStamp));   // 时间戳转换成时间
        option.setMtime(mtime);
        return Result.ok(projectOrderService.saveOrUpdate(option));
    }

    @PostMapping(value = "order/edit")
    @StaffLogc(title = "项目修改", action = "项目修改", actionAdo = "项目对接")
    public Result orderAdd(@Valid @RequestBody ProjectOrder params) {
        final ProjectOrder projectOrder = projectOrderService.getById(params.getId());
        if (ValidateUtil.isEmpty(projectOrder)) {
            throw new RuntimeException("未找到此该接项目人信息！！！");
        }
        return Result.ok(projectOrderService.saveOrUpdate(params));
    }

    //订单编辑
    @GetMapping(value = "order/detail")
    public Result orderDetail(@Valid @ModelAttribute IdQuery query) {
        String id = query.getId();
        final ProjectOrder apply = projectOrderService.getById(id);
        if (ValidateUtil.isEmpty(apply)) {
            throw new RuntimeException("当前不存在");
        }
        return Result.ok(apply);
    }

    //删除
    @PostMapping(value = "order/del")
    @StaffLogc(title = "项目删除", action = "项目删除", actionAdo = "项目对接")
    public Result orderDel(@Valid @RequestBody IdQuery query) {
        return Result.ok(projectCaseMapper.orderDel(query.getId()));
    }

    @GetMapping(value = "case/caseList")
    public LayTableResult CaseList(@Valid @ModelAttribute ProjectCase params) {
        Integer begin = params.getCurrentPage();
        Integer pageSize = params.getPageSize();
        Integer currentPage = (begin - 1) * pageSize;
        List<ProjectCase> list = projectCaseMapper.proCaseListPage(currentPage, pageSize);
        Integer count = projectCaseMapper.proCaseListCount();
        return new LayTableResult<>(0, "获取案列列表", list, count);
    }

    @PostMapping(value = "case/caseEdit")
    @StaffLogc(title = "案列展示修改", action = "案列展示修改", actionAdo = "案列展示")
    public Result caseEditVo(@Valid @RequestBody ProjectCase params) {
        ProjectCase projectCase = projectCaseService.getById(params.getId());
        if (ValidateUtil.isEmpty(projectCase)) {
            ProjectCase project = new ProjectCase(0);
            BeanUtils.copyProperties(params, project);
            params.setTimeCreated(System.currentTimeMillis());
            params.setTimeModified(System.currentTimeMillis());
            long timeStamp = System.currentTimeMillis();  //获取当前时间戳,也可以是你自已给的一个随机的或是别人给你的时间戳(一定是long型的数据)
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//这个是你要转成后的时间的格式
            String mtime = sdf.format(new Date(timeStamp));
            params.setMtime(mtime);
        }
        return Result.ok(projectCaseService.saveOrUpdate(params));
    }

    @PostMapping(value = "case/caseDetail")
    public Result caseDelVo(@Valid @RequestBody IdQuery query) {
        final ProjectCase byId = projectCaseService.getById(query.getId());
        if (ValidateUtil.isEmpty(byId)) {
            throw new RuntimeException("未找到所需的数据！！！");
        }

        return Result.ok(byId);
    }

    @PostMapping(value = "case/caseDel")
    @StaffLogc(title = "案列展示删除", action = "案列展示删除", actionAdo = "案列展示")
    public Result caseDelVo1(@Valid @RequestBody IdQuery query) {
        final ProjectCase byId = projectCaseService.getById(query.getId());
        if (ValidateUtil.isEmpty(byId)) {
            throw new RuntimeException("未找到此数据信息！！！");
        }
        List<ProjectCaseBrand> projectCaseBrands = projectCaseMapper.caseVo(byId.getId());
        projectCaseBrands.forEach(m -> {
            final int i = projectCaseMapper.caseDelete(m.getId());
            if (i != 1) {
                throw new RuntimeException("删除案例展示失败！！！");
            }
        });
        final int i = projectCaseMapper.caseVoDelete(byId.getId());
        if (i != 1) {
            throw new RuntimeException("删除案例展示失败！！！");
        }
        return Result.ok(byId.getId());
    }

    //我的发布项目
    @GetMapping(value = "releaseProject")
    public Result releaseProject() {
        Integer currentUserId = LoginContextUtils.getUserId();
        final List<Project> projects = projectCaseMapper.releaseProject(currentUserId);
        if (ValidateUtil.isEmpty(projects)) {
            List<Project> project = new ArrayList<>();
            return Result.ok(project);
        }

        return Result.ok(projects);
    }

    //我的发布项目已接信息
    @GetMapping(value = "releaseOrder")
    public Result releaseOrder(@Valid @ModelAttribute IdQuery query) {
        String id = query.getId();
        final List<ProjectOrder> projects = projectCaseMapper.releaseOrder(id);
        if (ValidateUtil.isEmpty(projects)) {
            List<ProjectOrder> project = new ArrayList<>();
            return Result.ok(project);
        }
        projects.forEach(m -> {
            long timeStamp = m.getTimeCreated();  //获取当前时间戳,也可以是你自已给的一个随机的或是别人给你的时间戳(一定是long型的数据)
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//这个是你要转成后的时间的格式
            String mtime = sdf.format(new Date(timeStamp));   // 时间戳转换成时间
            m.setMtime(mtime);
        });
        return Result.ok(projects);
    }

    //我的发布项目
    @GetMapping(value = "releaseOrderAll")
    public Result releaseOrderAll() {
        Integer currentUserId = LoginContextUtils.getUserId();
        final List<ProjectOrder> projects = projectCaseMapper.releaseOrderAll(currentUserId);
        if (ValidateUtil.isEmpty(projects)) {
            List<ProjectOrder> project = new ArrayList<>();
            return Result.ok(project);
        }
        List<ProjectOrderVo> projectList = new ArrayList<>();
        projects.forEach(m -> {
            ProjectOrderVo project = new ProjectOrderVo();
            BeanUtils.copyProperties(m, project);
            long timeStamp = m.getTimeCreated();  //获取当前时间戳,也可以是你自已给的一个随机的或是别人给你的时间戳(一定是long型的数据)
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//这个是你要转成后的时间的格式
            String mtime = sdf.format(new Date(timeStamp));   // 时间戳转换成时间
            project.setMtime(mtime);
            final Project byId = projectService.getById(m.getProjectId());
            if (ValidateUtil.isValid(byId)) {
                project.setTitle(byId.getTitle());
            } else {
                project.setTitle("");
            }
            projectList.add(project);
        });
        return Result.ok(projectList);
    }


    //消息列表
    @GetMapping(value = "massage/list")
    public LayTableResult massageList(@Valid @ModelAttribute Message params) {
        Integer begin = params.getCurrentPage();
        Integer pageSize = params.getPageSize();
        Integer currentPage = (begin - 1) * pageSize;
        List<Message> list = projectCaseMapper.messagePage(currentPage, pageSize);
        list.forEach(m -> {
            long timeStamp = m.getTimeCreated();  //获取当前时间戳,也可以是你自已给的一个随机的或是别人给你的时间戳(一定是long型的数据)
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//这个是你要转成后的时间的格式
            String mtime = sdf.format(new Date(timeStamp));   // 时间戳转换成时间
            m.setMtime(mtime);
            m.setUname(URLCoderUtils.decodeStr(m.getUname()));
        });
        Integer count = projectCaseMapper.messageCount();
        return new LayTableResult<>(0, "获取消息列表", list, count);
    }

    //消息是否已读修改
    @PostMapping(value = "massage/save")
    @StaffLogc(title = "消息列表添加", action = "消息列表添加", actionAdo = "消息列表")
    public Result massageEdit(@Valid @RequestBody Message params) {
        Message apply = messageService.getById(params.getId());
        if (ValidateUtil.isValid(apply)) {
            projectCaseMapper.messageUpdate(params.getId(), params.getMtype());
        }
        return Result.ok();
    }

    //后台手动添加
    @ApiOperation("后台手动发送")
    @PostMapping(value = "massage/add")
    @StaffLogc(title = "消息列表添加", action = "消息列表添加", actionAdo = "消息列表")
    public Result massageAdd(@Valid @RequestBody MessageParams params) {
        ExecutorService cachedThreadPool = Executors.newCachedThreadPool();
        cachedThreadPool.execute(() -> {
        cachedThreadPool(params);
        });
        return Result.ok();
    }

    private void cachedThreadPool(MessageParams params) {
        String type = String.valueOf(params.getType());
            //站内信自定义用户
            if (Objects.equals(type, MassageConstant.Station_message_custom)) {
                Integer[] id = params.getIds();
                for (Integer integer : id) {
                    CustUserInfo custUserInfo = projectCaseMapper.CustUser(integer);
                    if (ValidateUtil.isValid(custUserInfo)) {
                        MassAgeShow(custUserInfo, params, 4);
                    }
                }
            }
            //站内信全部用户
            if (Objects.equals(type, MassageConstant.Station_letter_all_users)) {
                List<CustUserInfo> custUserInfo = projectCaseMapper.CustUserList();
                custUserInfo.forEach(m -> {
                    if (ValidateUtil.isValid(custUserInfo)) {
                        MassAgeShow(m, params, 4);
                    }

                });
            }
            //全部用户发短信
            if (Objects.equals(type, MassageConstant.users_send_SMS_messages)) {
                List<CustUserInfo> custUserInfo = projectCaseMapper.CustUserList();
                if (ValidateUtil.isValid(custUserInfo)) {
                    custUserInfo.forEach(m -> {
                        if (ValidateUtil.isValid(m.getPhone()) && !m.getPhone().equals("")) {
                            //判断是否是正确手机号
                            if (matchPhoneNumber(m.getPhone())) {
                                final String code = AliYunMobile("message", params.getTitle(), m.getPhone(), "SMS_225981634");
                                if (ValidateUtil.isValid(code)) {
                                    if (Objects.equals(code, "OK")) {
                                        MassAgeShow(m, params, 5);
                                    }
                                }

                            }
                        }
                    });
                }
            }
            //自定义用户发短信
            if (Objects.equals(type, MassageConstant.sending_SMS_messages)) {
                Integer[] id = params.getIds();
                for (Integer integer : id) {
                    CustUserInfo custUserInfo = projectCaseMapper.CustUser(integer);
                    if (ValidateUtil.isValid(custUserInfo)) {
                        if (ValidateUtil.isValid(custUserInfo.getPhone()) && !custUserInfo.getPhone().equals("")) {
                            //判断是否是正确手机号
                            if (matchPhoneNumber(custUserInfo.getPhone())) {
                                final String code = AliYunMobile("message", params.getTitle(), custUserInfo.getPhone(), "SMS_225981634");
                                if (ValidateUtil.isValid(code)) {
                                    if (Objects.equals(code, "OK")) {
                                        MassAgeShow(custUserInfo, params, 5);
                                    }
                                }

                            }
                        }

                    }
                }
            }
            //全部用户发短信跟站内信
            if (Objects.equals(type, MassageConstant.messages_inside_the_SMS_station)) {
                List<CustUserInfo> custUserInfo = projectCaseMapper.CustUserList();
                custUserInfo.forEach(m -> {
                    if (ValidateUtil.isValid(custUserInfo)) {
                        MassAgeShow(m, params, 4);
                        if (ValidateUtil.isValid(m.getPhone()) && !m.getPhone().equals("")) {
                            //判断是否是正确手机号
                            if (matchPhoneNumber(m.getPhone())) {
                                final String code = AliYunMobile("message", params.getTitle(), m.getPhone(), "SMS_225981634");
                                if (ValidateUtil.isValid(code)) {
                                    if (Objects.equals(code, "OK")) {
                                        MassAgeShow(m, params, 5);
                                    }
                                }

                            }
                        }
                    }

                });
            }
            //部分用户发短信跟站内信
            if (Objects.equals(type, MassageConstant.send_messages_inside_SMS_stations)) {
                Integer[] id = params.getIds();
                for (Integer integer : id) {
                    CustUserInfo custUserInfo = projectCaseMapper.CustUser(integer);
                    if (ValidateUtil.isValid(custUserInfo)) {
                        MassAgeShow(custUserInfo, params, 4);
                        if (ValidateUtil.isValid(custUserInfo.getPhone()) && !custUserInfo.getPhone().equals("")) {
                            //判断是否是正确手机号
                            if (matchPhoneNumber(custUserInfo.getPhone())) {
                                final String code = AliYunMobile("message", params.getTitle(), custUserInfo.getPhone(), "SMS_225981634");
                                if (ValidateUtil.isValid(code)) {
                                    if (Objects.equals(code, "OK")) {
                                        MassAgeShow(custUserInfo, params, 5);
                                    }
                                }

                            }
                        }
                    }
                }
            }
    }

    //封装
    private boolean MassAgeShow(CustUserInfo m, MessageParams params, Integer type) {
        Message message = new Message(0);
        //BeanUtils.copyProperties(params, message);
        message.setTimeCreated(System.currentTimeMillis());
        message.setTimeModified(System.currentTimeMillis());
        message.setMessageblob(params.getMessageblob());
        message.setSendId(params.getSendId());
        message.setPhone(m.getPhone());
        final CustUserInfo custUserInfo1 = projectCaseMapper.CustUser(Integer.parseInt(params.getSendId()));
        message.setSend(custUserInfo1.getUserName());
        message.setTitle(params.getTitle());
        message.setUid(m.getId());
        message.setUname("--");
        if(ValidateUtil.isValid(m.getUserName())){
            message.setUname(m.getUserName());
        }
        message.setUrl("");
        message.setType(type);
        final boolean b = messageService.save(message);
        if (!b) {
            throw new RuntimeException("添加消息失败！！！");
        }
        return b;
    }

    private static String AliYunMobile(String messageName, String message, String phone, String templateCode) {
        //签名【类似于公司名字】
        /**
         * 类似于： 短信的格式
         * 	【签名（signName）】内容（message）+一些模板内容
         *
         * */
        String signName = "艺术上海";
        //#访问键(阿里云平台注册的)
        String accesskey = "LTAI5tQ96CtLVbHUWXyfXsgm";
        //#访问秘钥(阿里云平台注册的)
        String accessSecret = "PPKz3yInitd5D6t20VXLejWuMmzWpj";

        //内容
        //推送的模板在（阿里云中申请的）
        try {
            IClientProfile profile = DefaultProfile.getProfile("cn-shanghai", accesskey, accessSecret);
            DefaultProfile.addEndpoint("cn-shanghai", "cn-shanghai", "Dysmsapi", "dysmsapi.aliyuncs.com");
            IAcsClient client = new DefaultAcsClient(profile);

            SendSmsRequest request = new SendSmsRequest();

            Map<String, String> map = new HashMap<String, String>();
            map.put(messageName, message);//消息

            request.setMethod(MethodType.POST);
            //电话号
            request.setPhoneNumbers(phone);    //接收号码
            request.setSignName(signName);
            ;    //控制台创建的签名名称
            request.setTemplateCode(templateCode);
            ;// 控制台创建的模板CODE
            request.setTemplateParam(JSON.toJSONString(map));// 短信模板中的变量；数字需要转换为字符串；个人用户每个变量长度必须小于15个字符。"
            SendSmsResponse httpResponse = client.getAcsResponse(request);
            if ("OK".equals(httpResponse.getCode())) {
                System.out.println("success_消息发送成功");
                return httpResponse.getCode();
            } else {
                System.out.println("error_消息发送失败");
            }

        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("error_消息发送失败");
        }
        return "";
    }

    /**
     * 验证手机号 由于号码段不断的更新，只需要判断手机号有11位，并且全是数字以及1开头
     *
     * @param phoneNumber 手机号码
     * @return
     */
    private static boolean matchPhoneNumber(String phoneNumber) {
        String regex = "^1\\d{10}$";
        if (phoneNumber == null || phoneNumber.length() <= 0) {
            return false;
        }
        return Pattern.matches(regex, phoneNumber);
    }

    //消息删除
    @PostMapping(value = "massage/del")
    @StaffLogc(title = "消息列表删除", action = "消息列表删除", actionAdo = "消息列表")
    public Result massageDel(@Valid @RequestBody IdQuery query) {
        String id = query.getId();
        return Result.ok(projectCaseMapper.messageDel(id));
    }

    @PostMapping(value = "massage/detail")
    public Result massageDetail(@Valid @RequestBody IdQuery query) {
        final Message byId = messageService.getById(query.getId());
        long timeStamp = byId.getTimeCreated();  //获取当前时间戳,也可以是你自已给的一个随机的或是别人给你的时间戳(一定是long型的数据)
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//这个是你要转成后的时间的格式
        String mtime = sdf.format(new Date(timeStamp));   // 时间戳转换成时间
        byId.setMtime(mtime);
        if (ValidateUtil.isEmpty(byId)) {
            throw new RuntimeException("未找到所需的数据！！！");
        }
        return Result.ok(byId);
    }

    @GetMapping(value = "massage/userDetail")
    public Result massageDetail() {
        Integer currentUserId = LoginContextUtils.getUserId();
        final List<Message> byId = projectCaseMapper.getUid(currentUserId);
        byId.forEach(m -> {
            long timeStamp = m.getTimeCreated();  //获取当前时间戳,也可以是你自已给的一个随机的或是别人给你的时间戳(一定是long型的数据)
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//这个是你要转成后的时间的格式
            String mtime = sdf.format(new Date(timeStamp));   // 时间戳转换成时间
            m.setMtime(mtime);
        });
        if (ValidateUtil.isEmpty(byId.size())) {
            throw new RuntimeException("未找到所需的数据！！！");
        }

        return Result.ok(byId);
    }

    @GetMapping(value = "massage/userEdit")
    @StaffLogc(title = "消息列表修改", action = "消息列表修改", actionAdo = "消息列表")
    public Result userEdit() {
        Integer currentUserId = LoginContextUtils.getUserId();
        if (ValidateUtil.isEmpty(currentUserId)) {
            throw new RuntimeException("您尚未登录，请先登录");
        }
        final List<Message> byId = projectCaseMapper.getUid(currentUserId);
        byId.forEach(m -> {
            String id = m.getId();
            Integer type = 1;
            projectCaseMapper.messageUpdate(id, type);
        });
        return Result.ok();
    }

    @GetMapping(value = "massage/count")
    public Result count() {
        Integer currentUserId = LoginContextUtils.getUserId();
        if (ValidateUtil.isEmpty(currentUserId)) {
            throw new RuntimeException("您尚未登录，请先登录");
        }
        return Result.ok(projectCaseMapper.getUidCount(currentUserId));
    }
    @StaffLogc(title = "消息列表修改", action = "消息列表修改", actionAdo = "消息列表")
    @PostMapping(value = "massage/edit")
    public Result massageSave(@Valid @RequestBody Message params) {
        final Message byId = messageService.getById(params.getId());
        if (ValidateUtil.isEmpty(byId)) {
            Message message = new Message(0);
            BeanUtils.copyProperties(params, message);
            params.setTimeCreated(System.currentTimeMillis());
            params.setTimeModified(System.currentTimeMillis());

            Integer currentUserId = 0;

            if (ValidateUtil.isEmpty(params.getSendId())) {
                currentUserId = LoginContextUtils.getUserId();
            }
            final CustUserInfo custUserInfo1 = projectCaseMapper.CustUser(currentUserId);
            if (ValidateUtil.isValid(custUserInfo1)) {
                params.setSendId(String.valueOf(currentUserId));
                params.setPhone(custUserInfo1.getPhone());
                params.setSend(custUserInfo1.getUserName());
            }
            final CustUserInfo custUserInfo = projectCaseMapper.CustUser(params.getUid());
            if (ValidateUtil.isValid(custUserInfo)) {
                params.setUid(params.getUid());
                params.setUname(custUserInfo.getUserName());
            }
        }
        return Result.ok(messageService.saveOrUpdate(params));
    }

    //申请类型行业详情
    @GetMapping(value = "user/companyApply/detail")
    public Result companyApplyDetail(@Valid @ModelAttribute IdQuery query) {
        String id = query.getId();
        final TenantApplyInfo apply = projectCaseMapper.companyApplyById(id);
        if (ValidateUtil.isEmpty(apply)) {
            throw new RuntimeException("当前不存在");
        }
        return Result.ok(apply);
    }

    @PostMapping("/ProductQuery")
    @ApiOperation(value = "直播中商品信息")
    public Result query(@RequestBody ParameterInfoPamar params) {
        if (ValidateUtil.isEmpty(params.getProductName())) {
            return Result.ok(projectCaseMapper.ParmsLists());
        }
        final String productName = params.getProductName();
        return Result.ok(projectCaseMapper.ParmsList(productName));
    }

    @GetMapping("/mgr/user/companyApply/del")
    @StaffLogc(title = "直播中商品信息删除", action = "直播中商品信息删除", actionAdo = "直播中商品信息")
    @ApiOperation(value = "直播中商品信息删除")
    public Result companyApplyDel(@Valid @ModelAttribute IdQuery query) {
        String id = query.getId();
        if (ValidateUtil.isEmpty(id)) {
            throw new RuntimeException("数据错误");
        }
        return Result.ok(projectCaseMapper.companyApplyDel(id));
    }

    //未启用
    @GetMapping("/message/remark")
    @ApiOperation(value = "评论发送短信消息")
    public Result remark(@Valid @ModelAttribute IdQuery query) {
        String id = query.getId();
        if (ValidateUtil.isEmpty(id)) {
            throw new RuntimeException("数据错误");
        }
        return Result.ok(AliYunMobile("", "", id, "SMS_225981634"));
    }

    @ApiOperation("热更新添加")
    @PostMapping(value = "/jsPatch/add")
    public Result jsPatchSave(@RequestBody @Valid JsPatchParam d) {
        jsPatch jsPatch = new jsPatch();
        jsPatch.setVers(d.getVers());
        jsPatch.setUrl(d.getUrl());
        jsPatch.setIntroduce(d.getIntroduce());
        jsPatch.setLost(LocalDateTime.now());
        jsPatch.setCtime(LocalDateTime.now());
        jsPatch.setUtime(LocalDateTime.now());
        jsPatch.setDtime(0);
        projectCaseMapper.insertSelective(jsPatch);
        return Result.ok();
    }

    @ApiOperation("热更新查询")
    @GetMapping(value = "/jsPatch/detail")
    public Result jsPatchGain() {
        return Result.ok(projectCaseMapper.selectOne());
    }

    @GetMapping("/tokenGain")
    @ApiOperation(value = "token获取")
    public Result tokenGain(HttpServletRequest request) {
        final String token = request.getHeader("token");
        if (ValidateUtil.isEmpty(token)) {
            throw new RuntimeException("请求失败,token为空！");
        }
        return Result.ok(projectService.tokenGain(token));
    }

    @PostMapping("/ticketSave")
    @ApiOperation(value = "门票系统添加数据")
    public LayTableResult ticket(@RequestBody @Valid UserInvitationSaveParam params) {
        final String token = LoginContextUtils.getToken();
        if (ValidateUtil.isEmpty(token)) {
            throw new RuntimeException("token不存在");
        }
        final String token1 = JWTUtil.verifyToken(token);
        if (ValidateUtil.isEmpty(token1)) {
            throw new RuntimeException("token已失效");
        }
        ExecutorService cachedThreadPool = Executors.newCachedThreadPool();
        cachedThreadPool.execute(() -> {
            projectService.ticketSave(params);
        });
        return new LayTableResult<>(0, "操作完成");
    }

    @PostMapping("/ticketOrderSave")
    @ApiOperation(value = "门票系统订单添加数据")
    public LayTableResult ticketOrder(@RequestBody @Valid OrderParam params) {
        final String token = LoginContextUtils.getToken();
        if (ValidateUtil.isEmpty(token)) {
            throw new RuntimeException("token不存在");
        }
        final String token1 = JWTUtil.verifyToken(token);
        if (ValidateUtil.isEmpty(token1)) {
            throw new RuntimeException("token已失效");
        }
        ExecutorService cachedThreadPool = Executors.newCachedThreadPool();
        cachedThreadPool.execute(() -> {
            projectService.OrderSave(params);
        });
        return new LayTableResult<>(0, "操作完成");
    }

}

